package com.example.demo.controller;

import com.example.demo.entity.Student;
import com.example.demo.entity.Organization;
import com.example.demo.repository.StudentRepository;
import com.example.demo.repository.OrganizationRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/students")
@CrossOrigin
@Tag(name = "学生信息管理接口", description = "学生注册和登录")
public class StudentController {

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private OrganizationRepository organizationRepository;

    @PostMapping("/register")
    @Operation(summary = "学生注册，传入学号、密码、姓名和班级号")
    public ResponseEntity<?> register(@RequestBody Map<String, String> body) {
        String studentNo = body.get("studentNo");
        String password = body.get("password");
        String name = body.get("name");
        String classIdStr = body.get("classId");

        if (studentNo == null || studentNo.isEmpty()
                || password == null || password.isEmpty()
                || name == null || name.isEmpty()
                || classIdStr == null || classIdStr.isEmpty()) {
            return ResponseEntity.badRequest().body(Map.of("message", "学号、密码、姓名和班级号不能为空"));
        }

        if (studentRepository.findByStudentNo(studentNo).isPresent()) {
            return ResponseEntity.badRequest().body(Map.of("message", "学号已存在"));
        }

        Long classId;
        try {
            classId = Long.parseLong(classIdStr);
        } catch (NumberFormatException e) {
            return ResponseEntity.badRequest().body(Map.of("message", "班级号格式错误"));
        }

        Optional<Organization> clazzOpt = organizationRepository.findById(classId);
        if (clazzOpt.isEmpty()) {
            return ResponseEntity.badRequest().body(Map.of("message", "班级不存在，请联系管理员"));
        }

        Student student = new Student();
        student.setStudentNo(studentNo);
        student.setPassword(password);
        student.setName(name);
        student.setClazz(clazzOpt.get());

        try {
            studentRepository.save(student);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of("message", "注册失败，服务器错误：" + e.getMessage()));
        }

        return ResponseEntity.ok(Map.of("message", "注册成功"));
    }

    @PostMapping("/login")
    @Operation(summary = "学生登录，传入学号和密码")
    public ResponseEntity<?> login(@RequestBody Map<String, String> body) {
        String studentNo = body.get("studentNo");
        String password = body.get("password");

        if (studentNo == null || studentNo.isEmpty() || password == null || password.isEmpty()) {
            return ResponseEntity.badRequest().body(Map.of("message", "学号和密码不能为空"));
        }

        Optional<Student> studentOpt = studentRepository.findByStudentNo(studentNo);
        if (studentOpt.isEmpty()) {
            return ResponseEntity.status(401).body(Map.of("message", "学号或密码错误"));
        }

        Student student = studentOpt.get();
        if (!student.getPassword().equals(password)) {
            return ResponseEntity.status(401).body(Map.of("message", "学号或密码错误"));
        }

        return ResponseEntity.ok(Map.of(
                "id", student.getId(),
                "name", student.getName(),
                "classId", student.getClazz() != null ? student.getClazz().getId() : null,
                "message", "登录成功"
        ));
    }
}
